import JSEncrypt from 'jsencrypt';
import { IJsEncryptProps, IJsEncryptMethods } from '../type/jsencrypt'


/** RSA数据加密 */
export default class YangJsEncrypt implements IJsEncryptMethods {
    public publicKey: string = ''
    public privateKey: string = '';
    constructor(props: IJsEncryptProps) {
        this.publicKey = props.publicKey;
        this.privateKey = props.privateKey;
    }
    /** 公钥加密 */
    encryptPublicData(data: any) {
        const encrypt = new JSEncrypt();
        encrypt.setPublicKey(this.publicKey)
        if (typeof data === 'object') {
            data = JSON.stringify(data);
        }
        return {
            passType: 'RSA',
            requestData: encrypt.encrypt(data)
        }
    }
    /** 私钥加密 */
    encryptPrivateData(data: any) {
        const encrypt = new JSEncrypt();
        encrypt.setPublicKey(this.privateKey)
        if (typeof data === 'object') {
            data = JSON.stringify(data);
        }
        return {
            passType: 'RSA',
            requestData: encrypt.encrypt(data)
        }
    }
    /** 公钥解密 */
    decryptPublicData(data: any) {
        const decrypt = new JSEncrypt();
        decrypt.setPublicKey(this.publicKey);
        if (typeof data === 'object') {
            data = JSON.stringify(data);
        }
        return JSON.parse(decrypt.decrypt(data) || '{}')
    }
    /** 私钥解密 */
    decryptPrivateData(data: any) {
        const decrypt = new JSEncrypt();
        decrypt.setPublicKey(this.privateKey);
        if (typeof data === 'object') {
            data = JSON.stringify(data);
        }
        return JSON.parse(decrypt.decrypt(data) || '{}')
    }
}


